package com.bk.view;

import com.bk.dao.LoginAndRegisterDao;
import com.bk.model.User;
import com.bk.util.DbUtil;

import java.sql.Connection;
import java.sql.SQLException;

// 登录、注册事件类
public class ViewAction {

    // 登录事件
    public User loginAction(String uname, String upassword) {
        if (uname.isEmpty() || upassword.isEmpty()) {
            return null;
        }
        // 临时用户
        User tempUser = new User(uname);
        tempUser.setUpassword(upassword);
        // 获取数据库连接
        Connection connection = DbUtil.getConnection();
        // 打包验证
        User currentUser = null;
        try {
            currentUser = new LoginAndRegisterDao().login(connection, tempUser);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        // 登录成功
        if (currentUser != null) {
            return currentUser;
        }
        return null;
    }

    // 注册事件
    public boolean regAction(String uname, String upassword, String isAdmin) {
        // 临时用户
        User tempUser = new User(uname);
        tempUser.setUpassword(upassword);
        tempUser.setIsAdmin(isAdmin);
        // 获取数据库连接
        Connection connection = DbUtil.getConnection();
        // 打包注册
        try {
            if (new LoginAndRegisterDao().reg(connection, tempUser)) {
                // 注册成功
                return true;
            }else {
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }
}
